import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {Link, History} from 'react-router';

import * as Util from '../../common/Util';

import {
  Input,
  Button
} from 'react-bootstrap';

import Notify from '../../common/Notification';
import * as FindPwdActions from '../../actions/FindPwdActions';
import * as TicketActions from '../../actions/TicketActions';
import Container from '../../components/Container';

class FindPwdApp extends Component {

  constructor () {
    super();  
  }

  static propTypes = {
    dispatch: PropTypes.func.isRequired
  }

  handleSubmitClick() {

    let phone = this.refs.phone.getValue();

    if (phone === "") {
      Notify.makeNotify("手机号码不能为空");
      return;
    }

    phone = phone.replace(/\s/g, "");

    if(!Util.phoneValidate(phone)){
      Notify.makeNotify("手机号码格式不正确");
      return;
    }

    this.props.findpwdAction.findpwd(phone);
  }

  componentDidUpdate(){

    let { findpwd } = this.props;

    let { findpwd_status = 0, message = "", phone = "" } = findpwd;
    
    if(findpwd_status === -1){
      Notify.makeNotify(message);
    }else if(findpwd_status === 1){

      findpwd.findpwd_status = 0;

      //发送短信验证码
      this.props.ticketAction.fetchTicket(phone);
    }

    //=====================================================================
    
    if (this.props.ticket) {
      let { ticket_status = 0, message : ticketMessage = "" } = this.props.ticket;

      if(ticket_status === -1){
        Notify.makeNotify(ticketMessage);
      }else if(ticket_status === 1){

        this.props.history.pushState(null, "/FindPwd2");
      }
    }
  }

  render() {

    return (
        <Container  
          isGoBack={true} 
          isHeader={true} 
          isFooter={false}
          isAuth = {false}
          headerTitle={"找回密码"}>
            <div className="blank30"></div>
              <div id="account-panel">
                  <form className="form-horizontal">

                    <div className="form-element">
                       <Input type="tel" 
                        ref = "phone" 
                        maxLength = "11"
                        defaultValue = "" 
                        placeholder = "请输入手机号码" 
                        wrapperClassName="col-xs-12" 
                        addonBefore="手机号"/> 
                    </div>

                    <div className="text-center padding-left-lg padding-right-lg">
                      <Button bsStyle="primary" block onClick={this.handleSubmitClick.bind(this)}>下一步</Button>  
                    </div>

                  </form>
            </div>
        </Container>
    );
  }
}

export default connect(state => ({
    findpwd : state.findpwd,
    ticket : state.ticket
}), dispatch => ({
    findpwdAction: bindActionCreators(FindPwdActions, dispatch),
    ticketAction: bindActionCreators(TicketActions, dispatch)
}))(FindPwdApp);

